/*
    Copyright (C) 2021 Huawei Device Co., Ltd.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.danikula.videocache.defaultStrategy;

import com.danikula.videocache.*;
import com.danikula.videocache.interfacers.CacheListener;
import com.danikula.videocache.interfacers.FloatRange;

/**
 *  默认的缓存策略
 */

public class DefaultCacheStrategy extends CacheStrategy {
    private long cacheBufferSize = 10 * 1024 * 1024;
    /**
     * 原库缓冲策略为当前拖动点不超过当前缓冲大小加上文件总大小的20%则等待缓冲完毕后开始播放 否则不缓存直接在线播放
     */
    private float cacheBufferRate = 0.2f;

    public DefaultCacheStrategy() {
        // 缓冲大小和缓冲比例都不设置则使用默认的缓冲策略
        this.cacheBufferSize = 0;
        this.cacheBufferSize = 0;
    }

    public DefaultCacheStrategy(long cacheBufferSize) {
        this.cacheBufferSize = cacheBufferSize;
        this.cacheBufferSize = 0; // 设置缓冲大小则不设置缓冲比例
    }

    public DefaultCacheStrategy(@FloatRange(from = 0, to = 1.0) float cacheBufferRate) {
        this.cacheBufferRate = cacheBufferRate;
        this.cacheBufferSize = 0; // 设置缓冲比例则不设置缓冲大小
    }

    public long getCacheBufferSize() {
        return cacheBufferSize;
    }

    public void setCacheBufferSize(long cacheBufferSize) {
        this.cacheBufferSize = cacheBufferSize;
    }

    public float getCacheBufferRate() {
        return cacheBufferRate;
    }

    public void setCacheBufferRate(float cacheBufferRate) {
        this.cacheBufferRate = cacheBufferRate;
    }

    @Override
    protected ProxyCache createHttpProxyCache(HttpUrlSource source, Config config, CacheListener uiCacheListener,
    String url) throws ProxyCacheException {
        FileCache cache = new FileCache(generateCacheFile(config, url), config.diskUsage);
        HttpProxyCache httpProxyCache = new HttpProxyCache(source, cache, this);
        httpProxyCache.registerCacheListener(uiCacheListener);
        return httpProxyCache;
    }
}
